//
// Created by LiuYou on 2021/8/19.
//

#include <cstdlib>
#include <cstdio>
#include <cstring>
#include <sys/socket.h>
#include <cassert>
#include <netinet/in.h>
#include <arpa/inet.h>
#include "ProcessPool.hpp"
#include "CGI.hpp"

int main(int argc, char** argv) {
    if (argc < 3) {
        printf( "用法: %s ip port\n", basename( argv[0] ));
        exit( 1 );
    }
    char* ip = argv[1];
    int port = atoi( argv[2] );

    int listenFd = socket( PF_INET, SOCK_STREAM, 0 );
    assert( listenFd >= 0 );

    int optVal = 1;
    setsockopt( listenFd, SOL_SOCKET, SO_REUSEADDR, &optVal, sizeof( optVal ));
    /* 判断。*/

    sockaddr_in localAddress{};
    localAddress.sin_family = AF_INET;
    inet_pton( AF_INET, ip, &localAddress.sin_addr );
    localAddress.sin_port = htons( port );

    int ret = bind( listenFd, (sockaddr*) &localAddress, sizeof( localAddress ));
    assert( ret != -1 );

    ret = listen( listenFd, 5 );
    assert( ret != -1 );

//    std::unique_ptr<ProcessPool<CGIConnect>> pool( ProcessPool<CGIConnect>::getInstance( listenFd ));

    ProcessPool<CGIConnect>* pool = ProcessPool<CGIConnect>::getInstance( listenFd );


    if (pool) {
        pool->run();
        delete pool;
    }

    close( listenFd );


    exit( 0 );
}